package com.hxl.config;

import com.hxl.entity.CmfzAdmin;
import com.hxl.entity.CmfzLog;
import com.hxl.mapper.CmfzLogMapper;
import com.hxl.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
@Aspect
public class LogAspect {
    @Autowired
    private CmfzLogMapper cmfzLogMapper;

    @After("@annotation(com.hxl.config.LogAnnotation)")
    public void logAop(JoinPoint joinPoint){
        CmfzLog cmfzLog = new CmfzLog();
        //设置时间为系统当前时间
        cmfzLog.setLogTime(new Date());
        //设置登录IP
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String addr = IPKit.getIpAddrByRequest(request);
        cmfzLog.setLogIp(addr);

        //获取用户名
        CmfzAdmin admin = (CmfzAdmin) request.getSession().getAttribute("admin");
        if (admin == null) {
            cmfzLog.setUsername("hhhh");
        }else {
            cmfzLog.setUsername(admin.getUsername());
        }

        /**
         * 获取注解内容和类型
         *
         * 通过joinPoint( 连接点对象)获取连接点信息
         * 1.通过连接点对象获取方法签名对象（方法的信息）
         * 2.通过方法签名对象 获取方法对象
         * 3.获取方法上的注解信息
         */
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        cmfzLog.setLogContent(annotation.content());
        cmfzLog.setLogType(annotation.type());
        //添加数据库
        cmfzLogMapper.insert(cmfzLog);

    }
}
